# -*- coding: utf-8 -*-
import requests
import json

sCorpID = "wx2b6a644956aea8d6"
corpsecret = "LB437Fd5jpguFMfNV2wecwZ-5UBTlulbSLW78Qmt1hXnUD3RG8tTn0LIZO8mYwJz"

API_PATHS = {
    "GET_TOKEN_URL" : "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
    "SEND_MESSAGE"  : "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s",
}

MSGTYPES = {
    'text':{
        'content':'',
    },
    'image':{
        'media_id':'',
    },
    'news':{
        'articles':[],
    }
}


class Article(object):
    """暂时不用，非字典类json时有问题，后面有空再搞"""
    def __init__(self,title,description='',url='',picurl=''):
        self.title = title
        self.description = description
        self.url = url
        self.picurl = picurl

    def __repr__(self):
        return {
            'title':self.title,
            'description':self.description,
            'url':self.url,
            'picurl':self.picurl,
        }.__repr__()

class Message(object):
    
    def __init__(self,agentid,touser='',toparty='',totag='',safe=0):
        self.agentid = agentid
        self.touser = touser
        self.toparty = toparty
        self.totag = totag
        self.safe = safe

class TextMessage(Message):

    def __init__(self,agentid,touser='',toparty='',totag='',safe=0,content=''):
        self.msgtype = "text"
        self.text = {"content": content }
        Message.__init__(self,agentid,touser,toparty,totag,safe)

class TextMessageEncoder(json.JSONEncoder):
    def default(self,obj):
        if isinstance(obj,TextMessage):
            print "this is a TextMessage obj"
            val = self.encode(obj.__dict__)
            print type(val)
            return obj.text

class NewsMessage(Message):

    def __init__(self,agentid,touser='',toparty='',totag='',safe=0,news=[]):
        self.news = {'articles':news}
        self.msgtype = "news"
        Message.__init__(self,agentid,touser,toparty,totag,safe)

class WebChartApi(object):
    
    def __init__(self,sCorpID,corpsecret):
        self.sCorpID = sCorpID
        self.corpsecret = corpsecret

    def get_access_token(self):
        res = requests.get(API_PATHS["GET_TOKEN_URL"]%(self.sCorpID,self.corpsecret))
        access_token = res.json()["access_token"]
        return access_token

    def send_message(self,token,message):
        send_url = API_PATHS["SEND_MESSAGE"] % token
        print "message = %s" % message
        data = json.dumps(message.__dict__,ensure_ascii=False)
        #import pdb
        #pdb.set_trace()
        print "data is %s" % data
        #data = data.replace("'","\"")
        #print "data is %s" % data
        #data = data.encode("utf8")
        res = requests.post(send_url,data=data)
        return res.json() 

def testencoder():
    message = TextMessage(3,touser="@all",content="This is a j'' test!")
    str = json.dumps(message.__dict__)
    print str

if __name__ =="__main__":
    api = WebChartApi(sCorpID,corpsecret)
    token = api.get_access_token()
    #message = TextMessage(3,touser="@all",content="This is a j''  test!")
    #res = api.send_message(token,message)
    news = [
        #Article("This is a demo",description="description",url="http://www.sina.com",picurl="http://www.sinaimg.cn/dy/slidenews/1_img/2015_17/2841_567113_575641.jpg")
        #Article("This is a demo",description="description",url="",picurl="")
        {'title':"This is a demo",'description':"description",'url':"http://www.sina.com",'picurl':"http://www.sinaimg.cn/dy/slidenews/1_img/2015_17/2841_567113_575641.jpg"}
    ]
    #message = NewsMessage(3,touser="@all",news=news)
    message = NewsMessage(3,touser="tedi3231",news=news)
    #print message.__dict__
    #print json.dumps(message.__dict__)
    res = api.send_message(token,message)
    print 'res = %s, token is %s' %(res, token)
    #testencoder()
